package cn.cimoc.controller;

import cn.cimoc.dto.AdminAddNewDTO;
import cn.cimoc.dto.AdminLoginDTO;
import cn.cimoc.ex.ServiceException;
import cn.cimoc.model.Admin;
import cn.cimoc.service.IAdminService;
import cn.cimoc.util.JwtUtils;
import cn.cimoc.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

//@RestController的作用= @ResponseBody+@Controller 在当前类中所有处理请求的方法的返回值均直接响应正文
@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {

    @Autowired
    private IAdminService adminService;

    //http://localhost:8080/admin/add-new?username=admin009&password=1234&nickname=a001
    @RequestMapping("/add-new")
    public JsonResult<Void> addNew(@Valid AdminAddNewDTO adminAddNewDTO){
        adminService.addNew(adminAddNewDTO);
        return JsonResult.ok();
    }

    //发出请求路径：localhost:8080/admin/2
    @RequestMapping("/{id:[0-9]+}")
    @PreAuthorize("hasAuthority('/reward-point/show')")
    //要求权限中 具有    /reward-point/show 这一条才允许访问此资源
    public JsonResult<Admin> getById(@PathVariable Long id){
        log.info("要查询的管理员id:{}",id);
        throw new ServiceException(JsonResult.State.ERR_INTERNAL_ERROR,"此功能尚未实现！！！");
    }

        //发出请求路径： localhost:8080/admin/login?username=user001&password=123456
    @RequestMapping("/login")
    public JsonResult<String> login(AdminLoginDTO adminLoginDTO){
        var jwt = adminService.login(adminLoginDTO);
        return JsonResult.ok(jwt);
    }

    @RequestMapping("/hello")
    @PreAuthorize("hasAuthority('/reward-point/show')")
    public JsonResult<Void> hello(){
        return JsonResult.ok();
    }
    @Autowired
    private JwtUtils jwtUtils;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @RequestMapping("/getinfo")
    public JsonResult<Admin> getInfo(@RequestHeader(value="Authentication") String token){
        log.info("请求头中的Authentication属性值：{}",token);
        var jwt = token.substring(tokenHeader.length());
        log.info("请求头中jwt数据：{}",jwt);
        var id = jwtUtils.parseJwtGetId(jwt);
        log.info("用户id:{}",id);
        adminService.getById(id);
        return JsonResult.ok(adminService.getById(id));
    }
}
